import pandas as pd
from io import BytesIO
from datetime import datetime
from flask import send_file

def export_to_excel(data, filename_prefix, columns_mapping=None):
    """
    通用导出Excel函数
    :param data: 数据列表
    :param filename_prefix: 文件名前缀
    :param columns_mapping: 列名映射（可选）
    :return: Excel文件响应
    """
    # 如果提供列名映射，则重命名列
    if columns_mapping:
        df = pd.DataFrame(data)
        df.rename(columns=columns_mapping, inplace=True)
    else:
        df = pd.DataFrame(data)
    
    # 创建内存中的Excel文件
    output = BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, index=False, sheet_name='Sheet1')
    
    output.seek(0)
    
    # 生成带时间戳的文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{filename_prefix}_{timestamp}.xlsx"
    
    return send_file(
        output,
        as_attachment=True,
        download_name=filename,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )